package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.service.FormFieldService;
import com.ccp.dev.workflow.model.*;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmDefVarService;
import com.ccp.dev.workflow.service.TaskReminderService;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe:任务节点催办时间设置 控制器类
 *
 * @author :jiayueqiao
 * Date: 2019-10-21
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT +UrlConstants.PROJECT_MODULE_WORKFLOW+"/taskReminder")
@Action(ownermodel=SysAuditModelType.PROCESS_MANAGEMENT)
public class TaskReminderController extends SysBaseController {

    @Resource
    private TaskReminderService taskReminderService;
    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private BpmDefVarService bpmDefVarService;

    /**
     * 流程变量管理页面
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "任务节点催办时间设置页面")
    public String viewAdd(HttpServletRequest request, Model model) {
        String id=RequestUtil.getString(request, "id");
        String procDefId=RequestUtil.getString(request,"procDefId");
        String nodeId=RequestUtil.getString(request, "nodeId");
        String parentProcDefId=RequestUtil.getString(request, "parentProcDefId", "");
        List<TaskReminder> taskReminders= taskReminderService.queryByProcDefAndNodeId(procDefId, nodeId);
        ActDefModel actDefModel =actDefModelService.getByProcDefId(procDefId);
        String modelId = actDefModel.getId();
        List<WarningSetting> warningSettingList =  taskReminderService.getWaringSettingList();
        Map<String,FlowNodeInfo> nodeMaps = NodeCache.getByProcDefId(procDefId);
        List<FlowNodeInfo> nodes = new ArrayList<>();
        Iterator<Map.Entry<String, FlowNodeInfo>> it = nodeMaps.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, FlowNodeInfo> entry = it.next();
            FlowNodeInfo node = entry.getValue();
            if(FlowNodeInfo.TYPE_USERTASK.equals(node.getNodeType())||FlowNodeInfo.TYPE_START_EVENT.equals(node.getNodeType())){
                //排序中将当前节点排到第一个，这样页面默认选中当前节点为相对节点
                if(nodeId.equals(node.getNodeId())){
                    nodes.add(0, node);
                } else{
                    nodes.add(node);
                }
            }
        }

        FormFieldService formFieldService=AppUtil.getBean(FormFieldService.class);
        List<FormField> flowVars;
        flowVars = formFieldService.queryFlowVarByFlowProcDefIdOrParentProcDefId(procDefId, parentProcDefId);
        List<BpmDefVar> bpmDefVars= bpmDefVarService.queryByModelId(modelId);

        int reminderStartDay=0;
        int reminderStartHour=0;
        int reminderStartMinute=0;

        int reminderEndDay=0;
        int reminderEndHour=0;
        int reminderEndMinute=0;

        int completeTimeDay=0;
        int completeTimeHour=0;
        int completeTimeMinute=0;

        TaskReminder taskReminder;
        if(StringUtil.isEmpty(id)){
            taskReminder = new TaskReminder();
        }else{
            taskReminder = taskReminderService.getOneById(id);
            int reminderStart=taskReminder.getReminderStart();
            reminderStartDay=reminderStart/(60*24);
            reminderStartHour=(reminderStart-reminderStartDay*(60*24))/60;
            reminderStartMinute=reminderStart-reminderStartDay*(60*24)-reminderStartHour*60;

            int reminderEnd=taskReminder.getReminderEnd();
            reminderEndDay=reminderEnd/(60*24);
            reminderEndHour=(reminderEnd-reminderEndDay*(60*24))/60;
            reminderEndMinute=reminderEnd-reminderEndDay*(60*24)-reminderEndHour*60;

            int complateTime=taskReminder.getCompleteTime();
            completeTimeDay=complateTime/(60*24);
            completeTimeHour=(complateTime-completeTimeDay*(60*24))/60;
            completeTimeMinute=complateTime-completeTimeDay*(60*24)-completeTimeHour*60;
        }
        model.addAttribute("taskReminder", taskReminder)
                .addAttribute("taskReminders",taskReminders)
                .addAttribute("warningSettingList",warningSettingList)
                .addAttribute("modelId",modelId )
                .addAttribute("procDefId", procDefId)
                .addAttribute("nodeId", nodeId)
                .addAttribute("flowVars",flowVars)
                .addAttribute("defVars",bpmDefVars)
                .addAttribute("reminderStartDay", reminderStartDay)
                .addAttribute("reminderStartHour", reminderStartHour)
                .addAttribute("reminderStartMinute", reminderStartMinute)
                .addAttribute("reminderEndDay",reminderEndDay )
                .addAttribute("reminderEndHour",reminderEndHour )
                .addAttribute("reminderEndMinute",reminderEndMinute )
                .addAttribute("completeTimeDay",completeTimeDay )
                .addAttribute("completeTimeHour",completeTimeHour)
                .addAttribute("completeTimeMinute",completeTimeMinute )
                .addAttribute("nodes",nodes);
        return getAutoView();
    }


    /**
     * 添加或更新任务节点催办时间设置
     * @param request request
     * @param taskReminder 催办设置
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="添加或更新任务节点催办时间设置",detail = "添加或更新任务节点催办时间设置<#if fl>成功<#else>失败</#if>")
    public ResultData save(HttpServletRequest request, TaskReminder taskReminder)
    {
        taskReminder.setWarningSetJson(StringEscapeUtils.unescapeHtml4(taskReminder.getWarningSetJson()));
        int reminderStartDay=RequestUtil.getInt(request, "reminderStartDay");
        int reminderStartHour=RequestUtil.getInt(request, "reminderStartHour");
        int reminderStartMinute=RequestUtil.getInt(request, "reminderStartMinute");
        //计算任务催办开始时间为多少个工作日，以分钟计算
        int reminderStart=(reminderStartDay*24+reminderStartHour)*60+reminderStartMinute;

        int reminderEndDay=RequestUtil.getInt(request, "reminderEndDay");
        int reminderEndHour=RequestUtil.getInt(request, "reminderEndHour");
        int reminderEndMinute=RequestUtil.getInt(request, "reminderEndMinute");
        //计算任务催办结束时间为多少个工作日，以分钟计算
        int reminderEnd=(reminderEndDay*24+reminderEndHour)*60+reminderEndMinute;

        int completeTimeDay=RequestUtil.getInt(request,"completeTimeDay");
        int completeTimeHour=RequestUtil.getInt(request,"completeTimeHour");
        int completeTimeMinute=RequestUtil.getInt(request, "completeTimeMinute");
        //计算办结时间为多少个工作日，以分钟计算
        int completeTime=(completeTimeDay*24+completeTimeHour)*60+completeTimeMinute;

        taskReminder.setReminderStart(reminderStart);
        taskReminder.setReminderEnd(reminderEnd);
        taskReminder.setCompleteTime(completeTime);

        try {
            if (StringUtil.isEmpty(taskReminder.getTaskDueId())){
                taskReminder.setTaskDueId(UUIDUtils.getUUIDFor32());
                taskReminderService.add(taskReminder);
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("save.success");
            }else{
                taskReminderService.update(taskReminder);
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("update.success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("save.failure");
        }
    }

    /**
     * 删除任务节点催办时间设置
     * @param request request
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="删除任务节点催办时间设置",detail = "删除任务节点催办时间设置<#if fl>成功<#else>失败</#if>")
    public ResultData del(HttpServletRequest request)
    {
        try{
            String taskDueId =RequestUtil.getString(request,"taskDueId");
            taskReminderService.delById(taskDueId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("delete.success");
        }
        catch(Exception ex){
            ex.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("delete.failure");
        }
    }

}
